package ruifeng.zcj.communcationring.ui.circle;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import ruifeng.zcj.communcationring.base.base_web_activity.WebViewActivity;
import ruifeng.zcj.communcationring.base.base_web_activity.other.JS;
import ruifeng.zcj.communcationring.groble.FragmentArgs;
import ruifeng.zcj.communcationring.groble.Whole;
import ruifeng.zcj.communcationring.groble.utils.Validate;
import ruifeng.zcj.communcationring.ui.circle.bean.UpImg;
import ruifeng.zcj.communcationring.ui.circle.bean.Voice;
import ruifeng.zcj.communcationring.ui.circle.other.CircleJS;
import ruifeng.zcj.communcationring.utils.Media;

/**
 * Created by Administrator on 2016/8/26 0026.
 */
public class CircleAcvitity extends WebViewActivity implements EasyPermissions.PermissionCallbacks {

    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;

    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;

    private static final String EXTRA_MOMENT = "EXTRA_MOMENT";
    private static final String EXTRA_PHOTOS = "PHOTOS";

    private static final int MAX_PHOTO_COUNT = 9;


    private HttpUtils httpUtils = new HttpUtils();
    Media media = null;

    public static void launch(Activity activity,
                              Class<? extends Fragment> clazz,
                              FragmentArgs args) {
        Intent intent = new Intent(activity, CircleAcvitity.class);
        intent.putExtra(KEY_CLASS_NAME, clazz.getName());
        if (args != null) {
            intent.putExtra(KEY_ARGS, args);
        }
        activity.startActivity(intent);
    }

    @Override
    public void initView() {
        Log.e("zcj", "1111111");


        String className = getIntent().getStringExtra(KEY_CLASS_NAME);
        if (TextUtils.isEmpty(className)) {
            finish();
            return;
        }
        FragmentArgs values = (FragmentArgs) getIntent().getSerializableExtra(KEY_ARGS);
        MyURL = (String) values.get(CircleFragment.FILM_URL);

        super.initView();
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        mWebview = view;

        //将过滤到的url加入历史栈中
        return true;
    }

    // 是否调用js代码默认是传递
    @Override
    protected boolean isAddJavascriptInterface() {
        return true;
    }

    // new一个子类
    @Override
    public JS newJsObj() {// 传递一个子类给
        CircleJS aa = new CircleJS();
        aa.jsona = "zcj";
        return aa;
    }

    // 一个key
    @Override
    public String HTMLkey() {// 获取他的key
        return "Android";
    }

    public void stopRecord() {

        if (media != null) {
            media.stopRecord();
            //media.destroy();
        }
        if (!Validate.isNullOrEmpty(voice)) {
            upataMp3(voice);
        }
    }

    public void startRecord() {
        if (media != null) {
            media.startRecord();
        }
    }


    public Voice voice = null;

    // js代码调用java代码之后该做什么事情做什么事情
    public void pay(String arg) {
//        getPersimmions();
        if (arg.equals("stop")) {
            // Toast.makeText(App.getAppContext(), "停止录音", Toast.LENGTH_SHORT).show();
            stopRecord();
        } else {
            media = new Media();
            voice = Voice.parasjson(arg);
            if (!Validate.isNullOrEmpty(voice)) {
                if (voice.getOp().equals("start")) {
                    // Toast.makeText(App.getAppContext(), "正在录音不要松开", Toast.LENGTH_SHORT).show();
                    startRecord();
                }
            }
        }
    }

    public void finishActivity() {
        CircleAcvitity.this.finish();
    }


    /**
     *
     * **/
    private void upataMp3(Voice voice) {
        File files = null;
        String sendpath = null;

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            sendpath = media.sendpath + "/" + media.name;
// V60108-075608.mp4
            files = new File(sendpath);
            if (!files.exists()) {
                files.mkdir();
            }
        }
        RequestParams paras = new RequestParams();
        paras.addBodyParameter("uploadfile", files);
        if (!Validate.isNullOrEmpty(voice)) {
            paras.addBodyParameter("id", voice.getId());
            paras.addBodyParameter("cid", voice.getCid());
        } else {
            paras.addBodyParameter("id", "服务器发送过来的数据有bug");
            paras.addBodyParameter("cid", "服务器发送过来的数据有bug");
        }

        String url = Whole.UplodataFile;

        httpUtils.send(HttpRequest.HttpMethod.POST, url, paras,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // Toast.makeText(getApplicationContext(), "错误", Toast.LENGTH_SHORT).show();
                        System.out.println("zcj错误" + arg0.toString());
                        System.out.println("zcj错误" + arg1);


                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        super.onLoading(total, current, isUploading);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseinfo) {
//                        button3.setText("成功："+responseinfo.result);
                        mWebview.reload();
                    }
                });

    }


    //    private OKHttpUtils okHttpUtils;
    public void test2() {

    }


    @Override
    protected void onPause() {
        super.onPause();
//        if (mWebview != null) {
//            mWebview.removeAllViews();
//            mWebview.destroy();
//        }
        if (media != null) {
            media.deleteMusic();
            // media.destroy();
        }
    }

    public boolean isCacheMode() {
        return false;
    }


    @Override
    public void uploadfileimg(String param) {

        UpImg upImg = UpImg.parasjson(param);
        choicePhotoWrapper();
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "zcj");
//            ArrayList<String> strings = new ArrayList<>();
            // startActivityForResult(BGAPhotoPreviewActivity.newIntent(this, MAX_PHOTO_COUNT, models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);
            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, MAX_PHOTO_COUNT, null), REQUEST_CODE_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {

            if (mWebview != null) {
                mWebview.loadUrl(MyURL);
            }
            //  Log.e("zcj", mWebview.getUrl());
            uploadImg(data);
//            mPhotosSnpl.setData(BGAPhotoPickerActivity.getSelectedImages(data));
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
//            mPhotosSnpl.setData(BGAPhotoPickerPreviewActivity.getSelectedImages(data));
        }
    }

    public void uploadImg(Intent data) {
        File files = null;
        ArrayList<String> photo = BGAPhotoPickerActivity.getSelectedImages(data);
        RequestParams paras = new RequestParams();
        for (String url : photo) {
            files = new File(url);
            Log.e("zcj", url);
            paras.addBodyParameter("UserFace", files);
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, Whole.getUplodataFile, paras,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
//                        Log.e("zcj", "2222"+responseinfo.result);
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        super.onLoading(total, current, isUploading);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseinfo) {
                        Log.e("zcj", "2222" + responseinfo.result);
                        finish();
                    }
                });
    }


    private String permissionInfo;
    private final int SDK_PERMISSION_REQUEST = 127;


    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }
            if (addPermission(permissions, Manifest.permission.RECORD_AUDIO)) {
                permissionInfo += "Manifest.permission.RECORD_AUDIO Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        showSnackBar("请开启所有权限");
    }


}
